package com.hjw.controller.adm;

import cn.dev33.satoken.util.SaResult;
import com.hjw.dao.LargeFileDao;
import com.hjw.entity.Book;
import com.hjw.entity.LargeFile;
import com.hjw.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 * @创建时间：2025-04-24
 * @文件名称：satoken_sobuk - com.hjw.controller.adm
 */
@Slf4j
@RestController
@RequestMapping("/api/adm/book")
public class AdmBookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private LargeFileDao largeFileDao;

    @GetMapping("/findById/{bid}")
    public SaResult findById(@PathVariable("bid") Integer bid) {
        if (bid == 0) {
            return SaResult.get(-200, "数据异常，获取失败", null);
        }
        log.info("bid:{}", bid);
        Book book = bookService.findById(bid);
        return SaResult.get(200, "获取成功", book);
    }

    @GetMapping("/findByPage/{start}/{num}")
    public SaResult findByPage(@PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        if (start == null || num == null) {
            return SaResult.get(-200, "数据异常，获取失败", null);
        }
        log.info("start:{},num:{}", start, num);

        Map<String, Object> map = new HashMap<>(3);
        if (num < 1){
            num = 1;
        }
        map.put("num", num);
        // 获取总记录数
        int count = bookService.count(map);
        // 计算总页数
        int totalPages = (int) Math.ceil((double) count / num);
        if (start > totalPages){
            start = totalPages;
        }
        int stateRow = 0;
        if (start > 0){
            stateRow = (start - 1) * num;
        }
        map.put("state", stateRow);


        log.info("查询条件：{}", map);
        List<Book> books = bookService.findByPage(map);
        Map<String, Object> result = new HashMap<>(2);
        result.put("books", books);
        result.put("count", count);
        return SaResult.get(200, "获取成功", result);
    }

    @PostMapping("/addOrUpdate")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public SaResult addOrUpdate(@RequestParam Map<String, Object> map,
                            @RequestParam(value = "mypic", required = false) MultipartFile myfile) {
        String newPicId = "";

        String tmake = map.get("tmake").toString();
        log.info("===>上传过来的param：{}", map.get("tmake"));
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            log.info("===>时间param:{}", tmake);
//            Date date = sdf.parse(tmake);
//            log.info("===>new出来的param：{}", date);
            Date date = new Date(tmake);
            map.put("tmake", date);
            System.out.println(date);

            log.info("===>new出来的param2：{}", date);
        } catch (Exception e) {
            log.info("===>管理员添加商品异常：{}",e.toString());
            return SaResult.get(-200, "时间格式异常，请重新上传", null);
        }
        log.info("===>param:{}", map);

        if (myfile != null){
            UUID picId = UUID.randomUUID();
            newPicId = picId.toString().replace("-", "");
            LargeFile largeFile = null;
            try {
                largeFile = new LargeFile(newPicId, myfile.getOriginalFilename(), myfile.getBytes());
            } catch (IOException e) {
                log.info("头像异常：{}", e.toString());
                SaResult.get(-200, "头像异常，请重新上传", null);
            }
            int add = largeFileDao.add(largeFile);
            if (add == 0){
                return SaResult.get(-200, "头像上传失败", null);
            }else {
                map.put("pic", newPicId);
            }
            log.info("头像上传成功：{}", largeFile);
        }

        map.put("price", Double.parseDouble(map.get("price").toString()));
        map.put("price2", Double.parseDouble(map.get("price2").toString()));

        int id = Integer.parseInt(map.get("id").toString());
        if (id != 0){
            int update = bookService.update(map);
            if (update == 0){
               throw new RuntimeException("异常错误：修改图书数据异常");
            }
            return SaResult.get(200, "修改成功", null);
        }

        map.remove("id");
        int add = bookService.add(map);

        if (add == 0){

            throw new RuntimeException("异常错误：添加图书数据异常");

        }
        return SaResult.get(200, "添加成功", null);
    }


}
